package tools

import (
	"errors"
	"golang.org/x/crypto/ssh"
	"io/ioutil"
	"log"
	"strings"
	"time"
)

func SaveH3cOrHuaweiCurrentConfig(path string, session *ssh.Session) error {
	log.Println("执行配置备份")
	output, err := session.CombinedOutput("display current-configuration")
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(path, output, 0644)
	if err != nil {
		return err
	}
	log.Printf("备份%s成功.", path)
	return nil
}

func StartSession(addr, user, password string) (client *ssh.Client, session *ssh.Session, err error) {
	client, err = ssh.Dial("tcp", addr, &ssh.ClientConfig{
		User: user,
		Auth: []ssh.AuthMethod{
			ssh.Password(password),
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	})
	if err != nil {
		return
	}
	session, err = client.NewSession()
	return
}

func SshCmd(args []string) (err error) {
	if len(args) < 3 {
		return errors.New("参数长度<3")
	}

	// 1.解析user passwd addr
	userPasswdAddr := strings.Split(args[1], "@")
	if len(userPasswdAddr) != 2 {
		return errors.New("解析userPasswdAddr出错")
	}
	// 1.1 addr
	addr := userPasswdAddr[1]
	userPasswd := strings.Split(userPasswdAddr[0], ":")
	if len(userPasswd) != 2 {
		return errors.New("解析userPasswd出错")
	}
	// 1.2 获取user passwd
	user := userPasswd[0]
	passwd := userPasswd[1]

	// 1.3 获取远程执行的shell cmd
	cmdArgs := args[2:]
	cmd := strings.Join(cmdArgs, " ")
	log.Println("准备执行...\n", cmd)

	// 2.建立连接
	client, session, err := StartSession(addr, user, passwd)
	if err != nil {
		return err
	}
	defer client.Close()
	defer session.Close()

	// 3.执行shell
	// 3.1 命令行如果是netConfig单独执行
	if len(cmdArgs) == 1 && cmdArgs[0] == "netConfig" {
		return SaveH3cOrHuaweiCurrentConfig(time.Now().Format(TimeFileFmt)+".txt", session)
	}

	// 3.2 执行其它命令
	_, err = session.CombinedOutput(cmd)
	if err != nil {
		return err
	}
	log.Println("执行完成.")
	return nil
}

func SshTool() *Option {
	return &Option{"ssh_cmd", SshCmd, `ssh_cmd [用户名:密码@主机:端口 远程执行命令] ssh远程执行shell eg. ssh_cmd root:123456@192.168.1.1:22 date >> /tmp/test.log`}
}
